package com.qigao.mall.web.controller.app.user;

import com.qigao.mall.api.ShopCartService;
import com.qigao.mall.commons.dto.ShopCartCreateDto;
import com.qigao.mall.commons.dto.ShopCartResultDto;
import com.qigao.mall.commons.enums.Result;
import com.qigao.mall.commons.enums.ResultCode;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.web.utils.RequestUtils;
import com.qigao.mall.web.utils.ValidatorUtil;
import com.qigao.mall.web.vo.app.ShopCartCreateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/app/user/cart")
@Api(tags = "App购物车相关API",value = "App购物车相关API")
public class AppCartController {


    private static Logger logger= LoggerFactory.getLogger(AppCartController.class);
    @Resource
    ShopCartService shopCartService;

    //1.加入购物车
    @PostMapping("/addShoppingCart")
    @ApiOperation(value = "加入购物车", notes = "加入购物车")
    public Result<String> addShoppingCart(@RequestBody ShopCartCreateVo shopCartCreateVo, HttpServletRequest request){

        try{
            //参数校验
            ValidatorUtil.validateEntity(shopCartCreateVo,ShopCartCreateVo.class);
            ShopCartCreateDto shopCartCreateDto=new ShopCartCreateDto();
            shopCartCreateDto.setItemNo(shopCartCreateVo.getItemNo());
            shopCartCreateDto.setStockNo(shopCartCreateVo.getStockNo());
            shopCartCreateDto.setBuyNum(new BigDecimal(shopCartCreateVo.getBuyNum()));
            shopCartCreateDto.setBuylerId(RequestUtils.getCurrentUserNo(request));
            return shopCartService.addShoppingCart(shopCartCreateDto);
        }catch (BusinessException be){
            logger.error("[加入购物车]发生业务异常:{}",be);
            return Result.newError(be.getCode(),be.getMsg());
        }catch (Exception e){
            logger.error("[加入购物车]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //2.查询购物车所有商品信息
    @GetMapping("/findShopCartByUserNo")
    @ApiOperation(value = "查询购物车所有商品信息", notes = "查询购物车所有商品信息")
    public Result<List<ShopCartResultDto>> findShopCartByUserNo(HttpServletRequest request){
        try{
            //参数校验
            List<ShopCartResultDto> shopCartResultDtos = shopCartService.findShopCartByUserNo(RequestUtils.getCurrentUserNo(request));
            return Result.newSuccess(shopCartResultDtos);
        }catch (Exception e){
            logger.error("[查询购物车所有商品信息]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


}
